
library IEEE;
use IEEE.std_logic_1164.all;
use work.state_pkg.all;

entity cross_mem is
	port (	clk			: in	std_logic;
		reset			: in	std_logic;

		sensor_l		: in	std_logic;
		sensor_m		: in	std_logic;
		sensor_r		: in	std_logic;
		
		L: out std_logic;
		R: out std_logic;
		debug_led_1 : out std_logic;
		debug_led_2 : out std_logic
	);
end entity cross_mem;



architecture behavioural of cross_mem is
   type cross_mem_state_type is (STRAIGHT_STATE, READING_R_STATE, READING_L_STATE, R_STATE, L_STATE);
   signal state, newstate: cross_mem_state_type;
   
    signal sensor: std_logic_vector(2 downto 0);   
    signal continu_state : std_logic;
    
    begin
    sensor <= sensor_l & sensor_m & sensor_r;
    
    process (clk)
      begin
        if (rising_edge (clk)) then
            if (reset = '1') then
                state <= STRAIGHT_STATE;
            else
                state <= newstate;
            end if;
        end if;
    end process;
    
  lblstate: process(state, sensor_l, sensor_m, sensor_r)
  begin
  case state is 
    when STRAIGHT_STATE =>
      L <= '0';
      R <= '0';
      debug_led_1 <= '0';
      debug_led_2 <= '0';
      if (sensor_l = '0' AND sensor_m = '1' AND sensor_r = '0') then
        newstate <= READING_R_STATE;
      else 
        newstate <= STRAIGHT_STATE;
      end if;
    when READING_R_STATE =>
      L <= '0';
      R <= '1';
      debug_led_1 <= '1';
      debug_led_2 <= '0';
      if (sensor_l = '1' AND sensor_m = '0' AND sensor_r = '1') then
        newstate <= R_STATE;
      else 
        newstate <= READING_R_STATE;
      end if;
    when R_STATE =>
      L <= '0';
      R <= '1';
      debug_led_1 <= '1';
      debug_led_2 <= '0';
      if (sensor_l = '0' AND sensor_m = '1' AND sensor_r = '0') then
        newstate <= READING_L_STATE;
      else 
        newstate <= R_STATE;
      end if;
    when READING_L_STATE =>
      L <= '1';
      R <= '0';
      debug_led_1 <= '1';
      debug_led_2 <= '1';
      if (sensor_l = '1' AND sensor_m = '0' AND sensor_r = '1') then 
        newstate <= L_STATE;
      else 
        newstate <= READING_L_STATE;
      end if;
    when L_STATE =>
      debug_led_1 <= '1';
      debug_led_2 <= '1';
      L <= '1';
      R <= '0';
      newstate <= L_STATE;
    
  end case;
end process;
  
end architecture behavioural;
